import NavBar from '@/components/NavBar'
// import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classnames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useState } from 'react'
import { useHistory, useLocation } from 'react-router'
export default function Login() {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  const onExtraClick = async () => {
    if (time > 0) return
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
    }
    await dispatch(sendCode(mobile))
    Toast.success('获取验证码成功', 1)

    // 开启倒计时
    setTime(60)
    let timer = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timer)
        }
        return time - 1
      })
    }, 1000)
  }
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    // // 当表单提交的时候，会触发
    // onSubmit: async (values) => {
    //   console.log(values)
    //   await dispatch(login(values))
    //   Toast.success('登录成功')
    //   // history.push('/home')
    //   if (location.from) {
    //     history.replace(location.from.pathname)
    //   } else {
    //     // history.go(-1) 页面回退
    //     // history.go(1) 页面前进
    //     // history.push() 页面跳转，并且往页面栈中添加一条记录
    //     // history.replace() 页面跳转，但是不会添加一条记录，而且替换当前的记录
    //     history.replace(pathname)
    //   }
    //   // const pathname = location.state ? location.state.from : '/home'
    //   // history.replace(pathname)
    // },
    // 当表单提交的时候，会触发
    async onSubmit(values) {
      await dispatch(login(values))
      Toast.success('登录成功')
      const pathname = location.state ? location.state.from : '/home'
      history.push(pathname)
      // history.go(-1) 页面回退
      // history.go(1) 页面前进
      // history.push() 页面跳转，并且往页面栈中添加一条记录
      // history.replace() 页面跳转，但是不会添加一条记录，而且替换当前的记录
      history.replace(pathname)
    },

    // 表单验证
    validationSchema: Yup.object().shape({
      // 手机号验证规则
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),

      // 手机验证码验证规则
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码6个数字'),
    }),
  })
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    touched,
    errors,
    isValid,
  } = formik
  // console.log(formik)
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="mobile"
                placeholder="请输入手机号"
                value={mobile}
                autoComplete="off"
                onChange={handleChange}
                onBlur={handleBlur}
                maxLength={11}
              ></Input>
            </div>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
            {/* <div className="validate">手机号验证错误信息</div> */}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                name="code"
                value={code}
                placeholder="请输入验证码"
                extra={time === 0 ? '获取验证码' : time + 's后获取'}
                autoComplete="off"
                onExtraClick={onExtraClick}
                onChange={handleChange}
                onBlur={handleBlur}
                maxLength={6}
              ></Input>
            </div>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
            {/* <div className="validate">验证码验证错误信息</div> */}
          </div>
          {/* 登录按钮 */}
          <button
            type="submit"
            className={classnames('login-btn', isValid ? '' : 'disabled')}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
